package fan.project3_pksystem.Controller;

import fan.project3_pksystem.Mapper.UserMapper;
import fan.project3_pksystem.Module.Response;
import fan.project3_pksystem.Module.UserInfo;
import fan.project3_pksystem.Service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public  class UserController {

    @Autowired
    UserService userService;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public Response<UserInfo> login(String userName, String password, HttpSession session, HttpServletRequest request) {
        if(userName.isEmpty() ||password.isEmpty()){
            return Response.fail("用户名或密码为空");
        }
        UserInfo userInfo =userService.selectUserByName(userName);
        if(userInfo!= null && userInfo.getPassword().equals(password)) {
            userInfo.setPassword("你啥还想看呢?");
            session.setAttribute("userInfo", userInfo);
            return Response.success(userInfo);
        }else return Response.fail("登录失败");

    }

    @RequestMapping("/getUserInfo")
    public Response<UserInfo> getUserInfo(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        UserInfo newUserInfo = userMapper.selectUserInfoById(userInfo.getId());
        newUserInfo.setPassword(null);
//        System.out.println(userInfo);
        session.setAttribute("userInfo", newUserInfo);
        return Response.success(userInfo);
    }

    @RequestMapping("/register")
    public Response<String> register(String userName, String password, HttpSession session, HttpServletRequest request) {
        try {
            if(userName.isEmpty() ||password.isEmpty()){
                return Response.fail("用户名或密码为空");
            }
            if( userService.selectUserByName(userName)!=null){
                return Response.fail("用户已存在");
            }

            boolean finish = userService.registUser(userName, password);
            if(finish) {
                return  Response.success("注册成功");
            }
        }catch (Exception e) {
            e.printStackTrace();

        }
        return Response.fail("注册失败");


    }



}
